<script>

  const chatbox = document.getElementById('chatbox');
const userInput = document.getElementById('userInput');

function appendMessage(text, isUser, element) {
    if (element) {
      element.innerHTML += text;  // 使用innerHTML
      return element;
    }
    const div = document.createElement('div');
    div.className = `message ${isUser ? 'user' : 'bot'}`;
    div.innerHTML = text; // 用户消息保持纯文本
    chatbox.appendChild(div);
    chatbox.scrollTop = chatbox.scrollHeight;
    return div;
  }

function sendRequest() {
    const input = userInput.value;
    userInput.value = ''; // 清空输入框
    appendMessage(input, true);

    let botMessage = null; // 用于跟踪当前bot消息元素
    const eventSource = new EventSource(`/api/streamChat?prompt=${encodeURIComponent(input)}`);

    eventSource.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        if (data.text) {
          // 首次创建bot消息元素，后续持续更新
          botMessage = appendMessage(data.text, false, botMessage);
        } elseif (data.error) {
          appendMessage(`错误: ${data.error}`, false);
          eventSource.close();
        }
      } catch (error) {

      }
    };

    eventSource.onerror = () => {
      eventSource.close();
    };
  }

</script>